package com.scs.application.modules.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.model.PageRequest;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.upms.entity.Role;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.enums.RoleType;
import com.scs.application.modules.upms.mapper.RoleMapper;
import com.scs.application.modules.upms.request.RoleQueryRequest;
import com.scs.application.modules.upms.security.UserPrincipal;
import com.scs.application.modules.upms.service.RoleService;
import com.scs.application.modules.upms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserService userService;

    /**
     * 根据角色Id获取用户信息
     *
     * @param roleId
     * @return
     */
    @Override
    public IPage<User> pageUsers(String roleId, PageRequest pageRequest) {
        return baseMapper.pageUsers(pageRequest.getPage(), roleId);
    }

    @Override
    public IPage<Role> page(RoleQueryRequest request) {
        return this.page(request.getPage(), getQueryWrapper(request));
    }

    @Override
    public List<Role> list(RoleQueryRequest request) {


        return super.list(getQueryWrapper(request));

    }

    private QueryWrapper getQueryWrapper(RoleQueryRequest request) {
        //不包含的角色类型
        String excludeType = "";
        UserPrincipal user = UserUtils.currentUser();
        if (!user.isAdmin()) {
            excludeType = RoleType.SYSTEM.toString();
        }
        List<Role> roles = userService.getUserRoles(user.getId());

        List<String> ownerRoleIds = roles.stream().map(o -> o.getId()).collect(Collectors.toList());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>()
                .like(StringUtils.isNotBlank(request.getName()), "name", request.getName())
                .notIn("type", excludeType)
                .and(!user.isAdmin()
                        , o -> o/*.in("id", ownerRoleIds).or()*/.eq("creator", user.getId()));
        return queryWrapper;
    }

    @Override
    public boolean saveOrUpdate(Role entity) {
        BusinessException.throwErrorIf(
                this.count(Wrappers.<Role>query().ne(!entity.isNewRecord(),"id", entity.getId()).eq("code", entity.getCode())) > 0
                , "角色编码不可重复"
        );
        return super.saveOrUpdate(entity);
    }
}
